<style>
  .prize {
    padding: 0 30px;
  }

  .formInline .ivu-input-group-prepend .ivu-select-selection,
  .formInline .ivu-input-group-append .ivu-select-selection {
    background-color: #fff !important;
  }

  .award .ivu-select-multiple .ivu-select-selection {
    overflow: hidden !important;
  }
</style>
<style scoped>
</style>

<template>
  <div class="award">
    <product-title></product-title>
    <div class="prize ">
      <div>
        <h3 class="search-h3 huang">销售奖设置</h3>
      </div>

      <div style="color:red;margin-bottom:15px;">计算公式:
        <span style="color:blue;">按照个人月度FYC档次*相对应的奖金率</span>
      </div>

      <div class="common-box-body">
        <Form :model="formData" ref="formData" :rules="ruleValiFormData">
          <Row>
            <Col :md="24" :lg="6">
            <FormItem label="名称设置 :" prop="name" required>
              <Input v-model="formData.name" size="large" type="text" placeholder="名称设置" />
            </FormItem>
            </Col>
            <Col :md="24" :lg="6">
            <FormItem label="适用对象 :" class="search" prop="rankIds">
              <Select v-model="formData.rankIds" multiple filterable placeholder="选择适用对象" :transfer=true>
                <Option v-for="(option, index) in comoptions" :value="option.id" :key="index">{{option.name}}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col :md="24" :lg="6">
            <FormItem label="发放周期 :" prop="configValue.assessmentCycleType" required>
              <Select v-model="formData.configValue.assessmentCycleType">
                <Option value="4">月</Option>
                <Option value="3">季</Option>
                <Option value="2">半年</Option>
                <Option value="1">年</Option>
              </Select>
            </FormItem>
            </Col>
            <Col :md="24" :lg="6">
            <FormItem prop="enabled" required>
              <RadioGroup v-model="formData.enabled">
                是否启用 :
                <Radio label="1" class="ml15">是</Radio>
                <Radio label="0">否</Radio>
              </RadioGroup>
            </FormItem>
            </Col>

            <Col style="text-align:right" :md="24" :lg="6">
            <FormItem>
              <Button type="success" icon="plus" size="large" @click="addfyc">新增FYC档次</Button>
              <Button type="primary" icon="plus" size="large" @click="addgrade">新增年期档次</Button>
            </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <Row>
        <div class="">
          <Table :columns="columns" :data="tableList" size="large"></Table>
          <!-- <Table :columns="column" :data="tableList" size="large" stripe highlight-row border></Table> -->
        </div>
      </Row>
      <div id="footer" style="padding:0 30px;">
        <Button type="primary" shape="circle" id="submit" @click="data1" :disabled="tableaction" style="border-radius: 30px !important;margin-top:25px;">
          <Icon type="checkmark-circled"></Icon>
          保存 / 提交
        </Button>
        <Button id="back" shape="circle" @click="$router.back(-1)" style="border-radius: 30px !important;background:#77B4F5;color:white;font-size:14px;margin-top:25px;">返回</Button>
      </div>
    </div>
    <Modal v-model="fyc" title="设置FYC" :mask-closable="false" :closable="false" class-name="common-box-body formInline">
      <Form class="" :model="money" ref="money" :rules="ruleValifyc">
        <Row>
          <Col span="6">
          <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">月度FYC档次 :</div>
          </Col>
          <Col span="18">
          <FormItem prop="lowLimitValue">
            <Input placeholder="请输入" v-model="money.lowLimitValue">
            <Select slot="prepend" style="width: 120px" v-model="max">
              <Option value="<">最大值</Option>
            </Select>
            </Input>
          </FormItem>
          <FormItem prop="highLimitValue">
            <Input placeholder="请输入" v-model="money.highLimitValue">
            <Select slot="prepend" style="width: 120px" v-model="min">
              <Option value="≤">最小值</Option>
            </Select>
            </Input>
          </FormItem>
          </Col>
        </Row>

        <Row v-for="(item, index) in fycData">
          <Col>
          <Col span="6">
          <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">{{item.time}} :</div>
          </Col>
          <Col span="18">
          <FormItem prop="rate">
            <Input placeholder="请输入对应FYC的奖金率" v-model="item.rate"></Input>
          </FormItem>
          </Col>
          </Col>
        </Row>
      </Form>
      <div slot="footer" :md="24" :lg="8">
        <Button style="width:60px;" type="primary" size="small" @click="cancelfycModal">取消</Button>
        <Button style="width:60px;" class="tRight" type="success" size="small" long @click="addfycModal">确定</Button>
      </div>
    </Modal>
    <Modal v-model="grade" title="设置年期档次" :mask-closable="false" :closable="false" class-name="common-box-body formInline">
      <Form class="" :model="timing" ref="timing" :rules="ruleValiTim">
        <Row>
          <Col span="6">
          <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">年期档次 :</div>
          </Col>
          <Col span="18">
          <FormItem prop="timeLowLimitValue">
            <Input placeholder="请输入" v-model="timing.timeLowLimitValue">
            <Select slot="prepend" style="width: 120px" v-model="max">
              <Option value="<">最大值</Option>
            </Select>
            </Input>
          </FormItem>
          <FormItem prop="timeHighLimitValue">
            <Input placeholder="请输入" v-model="timing.timeHighLimitValue">
            <Select slot="prepend" style="width: 120px" v-model="min">
              <Option value="≤">最小值</Option>
            </Select>
            </Input>
          </FormItem>
          </Col>
        </Row>

        <Row v-for="(item, index) in gradeData">
          <Col>
          <Col span="6">
          <div style="font-size:14px;height:36px;line-height:36px;text-align:center;">{{item.title}}</div>
          </Col>
          <Col span="18">
          <FormItem prop="rate">
            <Input placeholder="请输入对应FYC的奖金率" v-model="item.rate"></Input>
          </FormItem>
          </Col>
          </Col>
        </Row>
      </Form>
      <div slot="footer" :md="24" :lg="8">
        <Button style="width:60px;" type="primary" size="small" @click="cancelGradeModal">取消</Button>
        <Button style="width:60px;" class="tRight" type="success" size="small" long @click="addGradeModal">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import productTitle from "../../components/productTitle";
  import {
    get_all_rule,
    get_add_rule,
    get_rule_list,
    del_rule,
    get_rank
  } from "../../api/rule";
  import {
    parteGetByName
  } from "../../api/parter";
  import util from '../../libs/util.js';
  export default {
    data() {
      return {
        tabgroup: {},
        gradeData: [],
        fycData: [],
        getNowRate: {},
        rateShow: false,
        comoptions: [],
        formData: {
          assessmentCycleType:'',
          tempalteId: this.$route.params.tempalteId,
          name: "",
          rankIds: [],
          enabled: "",
          configValue: {
            list: [],
            assessmentCycleType: "",
            ruleName:'销售奖',
          }
        },
        min: "≤",
        max: "<",
        money: {
          highLimitValue: "",
          lowLimitValue: ""
        },
        timing: {
          timeHighLimitValue: "",
          timeLowLimitValue: "",
          rate: ""
        },
        disabled: true,
        fyc: false,
        grade: false,
        tableList: [],
        column1: {
          type: "index",
          title: "序号",
          align: "center",
          width: "80"
        },
        column2: {
          title: "团队月度FYC档次",
          key: "a0",
          align: "center"
        },
        columns: [{
            type: "index",
            title: "序号",
            align: "center",
            width: "80"
          },
          {
            title: "团队月度FYC档次",
            key: "a0",
            align: "center"
          }
        ],
        caozuoKey: false,
        caozuo: {
          width: "80",
          title: "操作",
          key: "action",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button", {
                  props: {
                    type: "primary",
                    size: "large"
                  },
                  style: {
                    padding: "3px"
                  },
                  on: {
                    click: () => {
                      this.remove(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        },
        tableaction: false,
        ruleValiFormData: {
          name: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }],
          rankIds: [{
            required: true,
            message: '请选择一个适用对象',
          }],
          "configValue.assessmentCycleType": [{
            required: true,
            message: "请选择发放周期",
            trigger: "blur,change"
          }],
          enabled: [{
            required: true,
            message: "请选择是否启用",
            trigger: "blur,change"
          }]
        },
        ruleValifyc: {
          lowLimitValue: [{
            required: true,
            message: "最大值不能为空",
            trigger: "blur"
          }],
          highLimitValue: [{
            required: true,
            message: "最小值不能为空",
            trigger: "blur"
          }],
        },
        ruleValiTim: {
          timeLowLimitValue: [{
            required: true,
            message: "最大值不能为空",
            trigger: "blur"
          }],
          timeHighLimitValue: [{
            required: true,
            message: "最小值不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    components: {
      productTitle
    },
    created() {
      this.cominit();
      if (this.$route.params.id) {
        var _this = this;
        var url =
          BASE_URL1+"/kb/v1/rule/salary/config/" +
          this.$route.params.id;
        util.ajax
          .get(url, {})
          .then(function (res) {
            if (res.data.err == 0) {
              if (res.data.data.configValue.length > 10) {
                _this.formData.id = res.data.data.id;
                _this.formData.name = res.data.data.name;
                _this.formData.rankIds = res.data.data.rankSet;
                _this.formData.enabled = res.data.data.enabled ? "1" : "0";
                _this.formData.assessmentCycleType = res.data.data.assessmentCycleType?res.data.data.assessmentCycleType:'';
                _this.formData.configValue.assessmentCycleType = JSON.parse(
                  res.data.data.configValue
                ).assessmentCycleType;
                _this.formData.configValue.list = JSON.parse(
                  res.data.data.configValue
                ).list;
                _this.formData.configValue.ruleName = JSON.parse(
                res.data.data.configValue
              ).ruleName;
                // _this.tableList = _this.formData.configValue.list;
                _this.tabgroup = _this.formData.configValue;
                _this.getList();
              }
            }
          })
          .catch(error => {
            console.log(666);
          });
      }
    },
    methods: {
      cominit() {
        new Promise((resolve, reject) => {
          // get_rank().then(response => {
          get_rank()
            .then(response => {
              if (response.data.err == 0) {
                this.comoptions = response.data.data;
              } else {
                this.$Message.error(response.data.info);
              }
              resolve();
            })
            .catch(error => {
              reject(error);
            });
        });
      },
      addfyc() {
        this.fyc = true;
        this.fycData = [];
        for (var i in this.tableList) {
          let fycObj = {};
          fycObj.time = this.tableList[i].a0;
          fycObj.rate = "";
          this.fycData.push(fycObj);
        }
        console.log(this.fycData, "///this.fycData");
      },
      addgrade() {
        this.gradeData = this.columns.slice(2, this.columns.length - 1);
        if (this.gradeData.length == 0) {
          this.$Message.error("请先添加FYC档次");
        } else {
          this.grade = true;
          let _this = this;
          this.gradeData.map((item, index) => {
            _this.gradeData[index].rate = "";
          })
        }
      },
      addfycModal() {
        this.$refs["money"].validate(valid => {
          if (valid) {
            let _this = this;
            if (_this.columns[_this.columns.length - 1].title == "操作") {
              _this.columns = _this.columns.slice(0, _this.columns.length - 1);
            }
            _this.money = JSON.parse(JSON.stringify(_this.money));
            if (
              parseInt(_this.money.lowLimitValue) <=
              parseInt(_this.money.highLimitValue)
            ) {
              _this.money.lowLimitValue = "";
              _this.money.highLimitValue = "";
              _this.$Message.error("最小值设置不能大于输入的最大值");
              return false;
            }
            _this.columns.push({
              key: "a",
              title: _this.money.highLimitValue + "≤FYC<" + _this.money.lowLimitValue,
              align: "center"
            });
            _this.columns.push(_this.caozuo);
            let columnsData = _this.columns.slice(2, _this.columns.length - 1);
            let len = columnsData.length;
            for (var i = 2; i < len + 2; i++) {
              _this.columns[i].key = "a" + (i - 1);
            }
            if (_this.fycData) {
              var int = "a" + len;
              for (var t in _this.fycData) {
                _this.tableList[t][int] = _this.fycData[t].rate;
              }
            }
            _this.$refs["money"].resetFields();
            _this.money.highLimitValue = "";
            _this.money.lowLimitValue = "";
            // 关闭弹框 进行置空 下次进来再重新取数据
            this.fyc = false;
            this.fycData = [];
          }
        });
      },
      cancelfycModal() {
        this.fyc = false;
        // 关闭弹框 进行置空 下次进来再重新取数据
        this.fycData = [];
        this.$refs["money"].resetFields();
      },
      addGradeModal() {
        this.$refs["timing"].validate(valid => {
          if (valid) {
            if (parseInt(this.timing.timeLowLimitValue) <= parseInt(this.timing.timeHighLimitValue)) {
              this.timing.timeHighLimitValue = "";
              this.timing.timeLowLimitValue = "";
              this.$Message.error("最小值设置不能大于输入的最大值");
              return false;
            }
            var _this = this;
            var gradeObj = {};
            gradeObj.a0 =
              _this.timing.timeHighLimitValue +
              "≤年期<" +
              _this.timing.timeLowLimitValue;
            for (var j = 1; j <= _this.gradeData.length; j++) {
              var ind = "a" + j;
              gradeObj[ind] = _this.gradeData[j - 1].rate;
            }
            _this.tableList.push(gradeObj);
            _this.$refs["timing"].resetFields();
            _this.timing.timeHighLimitValue = "";
            _this.timing.timeLowLimitValue = "";
            this.grade = false;
            this.gradeData = [];
          }
        });
      },
      cancelGradeModal() {
        this.grade = false;
        this.$refs["timing"].resetFields();
      },
      // 点击删除
      remove(index) {
        this.$Modal.confirm({
          title: "提示",
          content: "是否要删除该条记录?",
          onOk: () => {
            this.tableList.splice(index, 1);
          }
        });
      },
      data1() {
        this.tableaction = true;
        setTimeout(() => {
          this.tableaction = false;
        }, 2000);
        this.$refs["formData"].validate(valid => {
          if (valid) {
            let _this = this;
            let array1 = [];
            this.formData.configValue.list = [];
            let len = _this.columns.length - 1;
            for (let a = 2; a < len; a++) {
              let arr1 = this.columns[a].title.split("≤FYC<");
              array1.push({
                highLimitValue: arr1[1],
                lowLimitValue: arr1[0],
                rate: ""
              });
            }
            for (let i = 0; i < _this.tableList.length; i++) {
              let _object = {};
              let arr = _this.tableList[i].a0.split("≤年期<");
              _object["timeHighLimitValue"] = arr[1];
              _object["timeLowLimitValue"] = arr[0];
              _object["list"] = [];
              _object["list"] = array1;
              for (let b = 0; b < _object["list"].length; b++) {
                _object["list"][b].rate = _this.tableList[i][
                  "a" + (b * 1 + 1)
                ].toString();
              }
              _this.formData.configValue.list.push(
                JSON.parse(JSON.stringify(_object))
              );
            }
            let form = Object.assign({}, _this.formData);
            form.configValue = JSON.stringify(form.configValue);
            form.assessmentCycleType = form.configValue.assessmentCycleType;
            form.rankIds = form.rankIds.join();
            if (_this.$route.params.id) {
              let url =
                BASE_URL1+"/kb/v1/rule/salary/config/" + form.id;
              util.ajax.post(url, form).then(res => {
                if (res.data.err == 0) {
                  _this.$Message.success("操作成功");
                  _this.$router.push({
                    name: "rulelist"
                  });
                } else {
                  _this.$Message.error("操作失败");
                }
              });
            } else {


              new Promise((resolve, reject) => {
                get_add_rule(form)
                  .then(response => {
                    if (response.data.err == 0) {
                      // _this.$refs['formData'].resetFields();
                      this.$router.push({
                        name: "rulelist"
                      });
                    } else {
                      _this.$refs["formData"].resetFields();
                      _this.$Message.error(response.data.info);
                    }

                    resolve();
                  })
                  .catch(error => {
                    reject(error);
                  });
              });
            }
          } else {
            _this.$Message.error("数据填写有误!未通过验证");
          }
        });
      },
      getList() {
        let params = {};
        new Promise((rev, rej) => {});
        let _this = this;
        let len = this.tabgroup.list[0].list.length;
        for (var i = 0; i < len; i++) {
          this.columns.push({
            key: "a" + (i + 1),
            title: _this.tabgroup.list[0].list[i].lowLimitValue +
              "≤FYC<" +
              _this.tabgroup.list[0].list[i].highLimitValue,
            align: "center"
          });
        }
        for (var a = 0; a < this.tabgroup.list.length; a++) {
          _this.tableList[a] = {};
          _this.tableList[a]["a0"] =
            _this.tabgroup.list[a].timeLowLimitValue +
            "≤年期<" +
            _this.tabgroup.list[a].timeHighLimitValue;
          for (var b = 0; b < _this.tabgroup.list[a].list.length; b++) {
            var index = "a" + (b + 1);
            let obj = {};
            // obj[index] = _this.tabgroup.list[a].list[b].rate;
            _this.tableList[a][index] = _this.tabgroup.list[a].list[b].rate;
          }
        }
        this.columns.push(this.caozuo);
      }
    }
  };
</script>